package com.spmsys.filter;

import com.alibaba.fastjson.JSONObject;
import com.spmsys.entity.sys.Users;
import com.spmsys.service.Auth;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
import java.util.TimeZone;

@WebFilter(filterName = "AuthFilter", urlPatterns = "/controller/app/*")
public class C_AuthFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException {
        System.out.println("AuthFilter");
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
        try {
            //获取当前时间
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss 'GMT'", Locale.US);
            simpleDateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
            //设置字符集、接受所有跨域请求、设置时间
            httpServletResponse.setContentType("application/json;charset=utf-8");
            httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
            httpServletResponse.setHeader("Access-Control-Allow-Methods", "*");
            httpServletResponse.setHeader("Access-Control-Allow-Headers", "*");
            httpServletResponse.setHeader("Date", simpleDateFormat.format(Calendar.getInstance().getTime()));
            //获取登录信息
            HttpSession httpSession = httpServletRequest.getSession();
            Auth auth = (Auth) httpSession.getAttribute("auth");
            //从cookie中获取鉴权信息
            String authorization = null;
            if (httpServletRequest.getCookies() != null) {
                for (Cookie cookie : httpServletRequest.getCookies()) {
                    if (cookie.getMaxAge() > 0 && cookie.getName().equals("authorization")) {
                        authorization = cookie.getValue();
                    }
                }
            }
            //从请求头中获取鉴权信息
            authorization = authorization != null ? authorization : httpServletRequest.getHeader("Authorization");
            if (authorization == null || !Auth.verify(authorization)) {
                System.out.println("鉴权失败");
                throw new RuntimeException("鉴权失败");
            }
            if (auth != null) {
                System.out.println("已登录");
                //放行
                filterChain.doFilter(httpServletRequest, httpServletResponse);
            } else {
                System.out.println("自动登录");
                Auth authAuto = new Auth();
                Users user = authAuto.getUserInfoById(Auth.getUserIdByToken(authorization));
                if (user == null) {
                    System.out.println("自动登录失败");
                    throw new RuntimeException("自动登录失败");
                }
                JSONObject loginResult = authAuto.login(user.getEmail(), user.getPhone(), user.getPassword());
                if (loginResult.get("data") == null) {
                    System.out.println("自动登录失败");
                    throw new RuntimeException("自动登录失败");
                }
                //保存登录信息
                httpSession.setAttribute("auth", authAuto);
                httpSession.setMaxInactiveInterval(30 * 24 * 60 * 60);
                Cookie cookieId = new Cookie("id", httpSession.getId());
                Cookie cookieAuthorization = new Cookie("authorization", authAuto.getToken(null));
                cookieId.setPath("/");
                cookieAuthorization.setPath("/");
                cookieId.setMaxAge(30 * 24 * 60 * 60);
                cookieAuthorization.setMaxAge(30 * 24 * 60 * 60);
                httpServletResponse.addCookie(cookieId);
                httpServletResponse.addCookie(cookieAuthorization);
                System.out.println("自动登录成功");
                //放行
                filterChain.doFilter(httpServletRequest, httpServletResponse);
            }
        } catch (Exception e) {
            JSONObject responseData = new JSONObject();
            responseData.put("errorCode", "AUTH_FILTER_FAIL");
            responseData.put("errorMessage", e.getMessage());
            PrintWriter printWriter = httpServletResponse.getWriter();
            printWriter.println(responseData);
            printWriter.close();
            e.printStackTrace();
        }
    }
}
